package com.sl.core.engine.utils;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import org.beetl.core.statement.*;
import org.beetl.sql.core.engine.SQLGrammarCreator;
import org.beetl.sql.core.engine.SQLPlaceholderST;

import java.util.*;

/**
 * SQL模板变量解析器，用于提取SQL模板中的变量并生成模拟参数
 */
public class SQLTemplateVariableResolver {

    /**
     * 替换SQL模板中的变量为模拟值
     */
    public static void replaceSqlTemplateVariable(ProgramMetaData metaData, Map<String, Object> parameterMap) {
        if (metaData == null || metaData.statements == null) {
            return;
        }
        processStatements(parameterMap, metaData.statements);
    }

    /**
     * 递归处理所有语句节点
     */
    private static void processStatements(Map<String, Object> parameterMap, Statement[] statements) {
        for (Statement statement : statements) {
            if (statement instanceof StaticTextASTNode) {
                continue; // 跳过静态文本节点
            }

            // 处理条件语句
            if (statement instanceof IfStatement ifStatement) {
                processIfStatement(parameterMap, ifStatement);
                continue;
            }

            // 处理SQL占位符
            if (statement instanceof SQLPlaceholderST sqlPlaceholder) {
                processSQLPlaceholder(parameterMap, sqlPlaceholder);
            }
        }
    }

    /**
     * 处理IF条件语句
     */
    private static void processIfStatement(Map<String, Object> parameterMap, IfStatement ifStatement) {
        if (ifStatement.ifStatement instanceof BlockStatement blockStatement) {
            processStatements(parameterMap, blockStatement.nodes);
        }
    }

    /**
     * 处理SQL占位符节点
     */
    private static void processSQLPlaceholder(Map<String, Object> parameterMap, SQLPlaceholderST sqlPlaceholder) {
        Expression expression = sqlPlaceholder.expression;
        if (expression instanceof VarRef varRef) {
            processVarRef(parameterMap, varRef);
        } else if (expression instanceof SQLGrammarCreator.SqlFunctionExpression functionExpression) {
            for (Expression arg : functionExpression.exps) {
                if (arg instanceof VarRef varArg) {
                    processVarRef(parameterMap, varArg);
                }
            }
        }
    }

    /**
     * 处理变量引用节点
     */
    private static void processVarRef(Map<String, Object> parameterMap, VarRef varRef) {
        GrammarToken token = varRef.token;
        VarAttribute[] attributes = varRef.attributes;

        if (ArrayUtil.isEmpty(attributes)) {
            // 简单变量，如 #{name}
            parameterMap.put(token.toString(), "");
            return;
        }

        // 处理嵌套变量，如 #{user.name} 或 #{list[0].name}
        String rootKey = token.toString();
        if (StrUtil.contains(rootKey, "$.")) {
            rootKey = "$";
        }

        // 确定根节点类型
        Object rootValue = parameterMap.computeIfAbsent(rootKey, k -> {
            if (hasSquareBracketAttribute(attributes)) {
                return new ArrayList<>();
            } else {
                return new HashMap<>();
            }
        });

        // 处理属性链
        processAttributes(parameterMap, rootKey, rootValue, attributes);
    }

    /**
     * 检查是否有数组下标属性
     */
    private static boolean hasSquareBracketAttribute(VarAttribute[] attributes) {
        return Arrays.stream(attributes)
                .anyMatch(attr -> attr instanceof VarSquareAttribute);
    }

    /**
     * 处理变量属性链
     */
    private static void processAttributes(Map<String, Object> parameterMap, String rootKey, Object rootValue,
                                          VarAttribute[] attributes) {
        Object currentValue = rootValue;

        for (int i = 0; i < attributes.length; i++) {
            VarAttribute attribute = attributes[i];

            if (attribute instanceof VarSquareAttribute squareAttr) {
                // 处理数组下标，如 list[0]
                currentValue = processSquareAttribute(parameterMap, (List<Map<String, Object>>) currentValue,
                        squareAttr, attributes, i);
            } else {
                // 处理普通属性，如 user.name
                currentValue = processNormalAttribute(parameterMap, (Map<String, Object>) currentValue,
                        attribute.token.toString());
            }
        }
    }

    /**
     * 处理数组下标属性
     */
    private static Object processSquareAttribute(Map<String, Object> parameterMap,
                                                 List<Map<String, Object>> listValue,
                                                 VarSquareAttribute squareAttr,
                                                 VarAttribute[] attributes, int currentIndex) {
        int index = getArrayIndex(squareAttr);
        // 确保列表容量足够
        while (listValue.size() <= index) {
            listValue.add(new HashMap<>());
        }

        Map<String, Object> mapValue = listValue.get(index);

        // 如果还有后续属性，继续处理
        if (currentIndex < attributes.length - 1) {
            VarAttribute nextAttr = attributes[currentIndex + 1];
            String nextKey = nextAttr.token.toString();

            if (nextAttr instanceof VarSquareAttribute) {
                // 下一个属性是数组，创建新列表
                ArrayList<Map<String, Object>> newList = new ArrayList<>();
                mapValue.put(nextKey, newList);
                return newList;
            } else {
                // 下一个属性是普通属性，创建新Map
                HashMap<String, Object> newMap = new HashMap<>();
                mapValue.put(nextKey, newMap);
                return newMap;
            }
        }

        return mapValue;
    }

    /**
     * 获取数组下标值
     */
    private static int getArrayIndex(VarSquareAttribute squareAttr) {
        try {
            return Integer.parseInt(squareAttr.token.toString());
        } catch (NumberFormatException e) {
            return 0; // 默认使用0作为下标
        }
    }

    /**
     * 处理普通属性
     */
    private static Object processNormalAttribute(Map<String, Object> parameterMap,
                                                 Map<String, Object> mapValue,
                                                 String attributeName) {
        return mapValue.computeIfAbsent(attributeName, k -> new HashMap<>());
    }
}
